package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Base64Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author AzureSky_X
 * @Date 2020/11/16 17:50
 * @Version 1.0
 */
@WebServlet(name = "UserController",value = "/user")
public class UserController extends BaseController {
    private UserService service=new UserServiceImpl();


    public String userRegister(HttpServletRequest request, HttpServletResponse response)  throws IOException{

        //拿参数
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String repassword=request.getParameter("repassword");
        String gender=request.getParameter("gender");
        String email=request.getParameter("email");

        //校验
        if (username==null||"".equals(username)){
            request.setAttribute("msg","用户名为null，注册失败");
            return "forward:error/error.jsp";
        }
        if (password==null||"".equals(password)){
            request.setAttribute("msg","密码输入有误，注册失败");
            return "forward:error/error.jsp";
        }
        if (email==null||"".equals(email)){
            request.setAttribute("msg","邮箱输入有误，注册失败");
            return "forward:error/error.jsp";
        }
        User u=new User();
        u.setUsername(username);
        u.setPassword(password);
        u.setEmail(email);
        u.setGender(Integer.parseInt(gender));
        u.setRole(1);//默认是普通用户
        u.setStatus(0);//默认为未激活状态
        //让servlet去做注册吧
        int result=service.register(u);
        if (result==0){
            request.setAttribute("msg","注册失败");
            return "forward:error/error.jsp";

        }else{
            System.out.println("注册成功");
            return "redirect:registerSuccess.jsp";
        }
    }

    /**
     * 检验用户名是否存在的方法
     * @param request
     * @param response
     */

    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int result=service.checkUserName(username);
        return String.valueOf(result);
    }

    /**
     * 激活的方法
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String active(HttpServletRequest request,HttpServletResponse response){
        String activeCode = request.getParameter("code");
        int result=service.active(activeCode);
        if (result==0){
            request.setAttribute("msg","激活失败");
            return "forward:error/error.jsp";
        }else{
            System.out.println("激活成功");
            return "redirect:login.jsp";
        }
    }


    /**
     * 校验验证码
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        String sessionCode = (String) request.getSession().getAttribute("sessionCode");
        if(code.equalsIgnoreCase(sessionCode)){
            return "0";
        }else{
            return "1";
        }
    }

    /**
     * 登录的方法
     * @param request
     * @param response
     * @return
     */
    public String userLogin(HttpServletRequest request,HttpServletResponse response){
        //接收参数
        String username =request.getParameter("username");
        String password=request.getParameter("password");
        String code=request.getParameter("code");
        String auto=request.getParameter("auto");
        //校验
        if(username==null||"".equals(username)){
            request.setAttribute("msg","用户名为null，登录失败");
            return  "forward:error/error.jsp";
        }
        if (password==null||"".equals(password)){
            request.setAttribute("msg","密码不能为空，登录失败");
            return  "forward:error/error.jsp";
        }
        String sessionCode= (String) request.getSession().getAttribute("sessionCode");

        if (!code.equalsIgnoreCase(sessionCode)){
            request.setAttribute("msg","验证码不正确，登录失败");
            return  "forward:error/error.jsp";

        }

        User user =service.login(username,password);
        if (user==null){
            request.setAttribute("msg","密码不正确，登录失败");
            return "forward:login.jsp";

        }
        //状态持续化
        request.getSession().setAttribute("loginUser",user);
        //两周自动登录
        if(auto==null){
            //不想免密登录
            Cookie c=new Cookie("autoLogin","");
            /**
             * cookie.setMaxAge(-1)
             * 设置为负值，为浏览器进程Cookie（内存中保存），关闭浏览器就失效
             * 设置为0，立刻删除该Cookie
             */
            c.setMaxAge(-1);//失效
            response.addCookie(c);
        }else {
            //执行免密登录，将用户名和密码存储在cookie中，两周时间明文存储不安全，需要进行加密
            //由于下一次登录我们需要在cookie拿到这样的键值对，将用户名和密码拆分出来进行重新登录
            //所以我们需要对密码进行可逆加密
            String str=username+":"+password;
            String encode = Base64Util.encode(str);
            Cookie c=new Cookie("autoLogin",encode);
            c.setMaxAge(60*60*24*14);//设置有效时间为两周
            c.setPath("/");
            response.addCookie(c);

        }
        System.out.println("登录成功");
        return "redirect:good?action=getGoodsListByTypeId";

    }

    /**
     * 登出操作
     * @param request
     * @param response
     * @return
     */

    public String logOut(HttpServletRequest request,HttpServletResponse response){
        //清空session域，重定向到good?action=getGoodsListByTypeId
        request.getSession().invalidate();
        Cookie c=new Cookie("autoLogin","");
        c.setMaxAge(0);//立刻销毁cookie
        response.addCookie(c);

        return "redirect:good?action=getGoodsListByTypeId";

    }









}
